package com.learn.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *  锁 案例
 */
public class TestThreadLock {
    private final static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {

        //标准模板
//        try {
//            lock.lock();
//            System.out.println("线程" + Thread.currentThread().getName() + "进入");
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        } finally {
//            lock.unlock();
//            System.out.println("线程" + Thread.currentThread().getName() + "退出");
//        }
        TestTicketNum testTicketNum = new TestTicketNum();
        new Thread(testTicketNum,"小红").start();
        new Thread(testTicketNum, "小明").start();
        new Thread(testTicketNum, "小王").start();
    }
}


class TestTicketNum implements Runnable {
    private int ticketNum = 10;
    private final static ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (ticketNum > 0) {
            lock.lock();
            //标准模板
            try {
                if (ticketNum <= 0) {
                    break;          // 没票了立即退出
                }
                System.out.println(Thread.currentThread().getName() + "正在购买第" +ticketNum);
                ticketNum--;
            }finally {
                lock.unlock();
            }
            // 模拟出票耗时（**在锁外**）
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

        }

    }
}